<template>
  <div>
    <van-nav-bar
        title="更新昵称"
        left-text="取消"
        right-text="保存"
        @click-left="$emit('clickLeft')"
        @click-right="onSave"
    />
    <van-field
        v-model.trim="message"
        autosize
        type="textarea"
        maxlength="7"
        placeholder="请输入昵称"
        show-word-limit
    />
  </div>
</template>

<script>
import { Toast } from 'vant'
import { editUserProfile } from '@/api/user'

export default {
  name: 'EditNickName',
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      message: this.value
    }
  },
  methods: {
    async onSave () {
      if (this.message === '') {
        return Toast('昵称不能为空')
      }
      try {
        await editUserProfile({
          name: this.message
        })
        Toast.success('更新成功')
        this.$emit('clickLeft')
        this.$emit('input', this.message)
      } catch (e) {
        if (e.response && e.response.status === 409) return Toast('用户名存在')
        Toast.fail('更新失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
